package com.fas.system.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.fas.system.domain.FasEquipmentManufacturer;
import com.fas.system.mapper.FasEquipmentManufacturerMapper;
import com.fas.system.service.IFasEquipmentManufacturerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class FasEquipmentManufacturerServiceImpl implements IFasEquipmentManufacturerService {

    static List<FasEquipmentManufacturer> child = new ArrayList<FasEquipmentManufacturer>();

    @Resource
    private FasEquipmentManufacturerMapper fasEquipmentManufacturerMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertManufacturer(FasEquipmentManufacturer fasEquipmentManufacturer) {
        //判断同一节点下只存在相同的数据
        int count = fasEquipmentManufacturerMapper.selectByNameAndParentId(fasEquipmentManufacturer);
        if (count > 0) return 0;
        else return fasEquipmentManufacturerMapper.insertManufacturer(fasEquipmentManufacturer);
    }

    @Override
    public List<Tree<String>> findLikeEquipmentManufacturer(FasEquipmentManufacturer equipmentManufacturer) {
        List<FasEquipmentManufacturer> list = fasEquipmentManufacturerMapper.findLikeEquipmentManufacturer(equipmentManufacturer);
        return genManufacturer(list);
    }

    private List<Tree<String>> genManufacturer(List<FasEquipmentManufacturer> list) {

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的
        treeNodeConfig.setWeightKey("order");
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setNameKey("name");
        treeNodeConfig.setChildrenKey("children");

        // 最大递归深度
        treeNodeConfig.setDeep(3);

        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(list, "null", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(String.valueOf(treeNode.getId()));
                    tree.setParentId(String.valueOf(treeNode.getParentId()));
                    tree.setWeight(treeNode.getSort());
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
//                    tree.putExtra("extraField", 666);
//                    tree.putExtra("other", new Object());
                });
        return treeNodes;
    }


}
